// pages/transaction/sale/sale.js
import api from '../../../api/api.js'
import Notify from '../../../miniprogram_npm/vant-weapp/notify/notify.js'
import {formatProductType} from '../../../utils/util'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: null,
    sellPrice: null,
    sellUnit: null,
    profitInfo: {},
    loading: true,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserProfit();
  },
  changePrice(e) {
    this.setData({
      sellPrice: e.detail
    })
  },
  changeCount(e) {
    this.setData({
      sellUnit: e.detail
    })
  },
  onChange(event) {
    const {key} = event.currentTarget.dataset;
    let price = null;
    if (event.detail !== '') {
      price = this.data.profitInfo.userProductList[event.detail].nowPrice
    }
    console.log(price);
    this.setData({
      [key]: event.detail,
      sellPrice: price,
      sellUnit: null,
    });

  },
  setAllUnit(e) {
    this.setData({
      sellUnit: e.target.dataset.unit
    })
  },
  getUserProfit() {
    api.getUserProfit().then(res => {
      let _data = res.data.data;
      _data.userProductList = _data.userProductList.map(item => {
        item.showProductType = formatProductType(item.productType);
        return item;
      });
      this.setData({
        profitInfo: _data,
        loading: false
      });
    });
  },
  sellUserProduct(e) {
    if (!this.data.sellPrice) {
      Notify('请输入价格');
    } else if (!this.data.sellUnit) {
      Notify('请输入数量');
    } else if (Number(this.data.sellUnit) > Number(e.target.dataset.unit)) {
      Notify('数量超过');
    } else {
      api.sellUserProduct({
        financeProductId: Number(e.target.dataset.productId),
        sellPrice: this.data.sellPrice,
        sellUnit: this.data.sellUnit,
      }).then(res => {
        if (res.code === '0') {
          Notify({
            text: '卖出成功',
            backgroundColor: '#4b0'
          });
          this.setData({
            buyPrice: null,
            buyUnit: null,
            active: null,
          });
          this.getUserProfit();
        }
      })
    }
  },
})